#include "interrupt.h"

// KEY1->PF9->EXTI9-->输入事件编号为：9
void hal_exti_IT_init(input_event_t inputEvent, unsigned int gpioGroup, edge_trigger_select_t edge)
{
	// 1. 设置PF9连接到EXTI9上   EXTI_EXTICR3[15:8] = 0x5
    switch (inputEvent / 4) {
    case 0:
        EXTI->EXTICR1 &= (~(0xFF << (inputEvent % 4 * 8)));
        EXTI->EXTICR1 |= (gpioGroup << (inputEvent % 4 * 8));
        break;
    case 1:
        EXTI->EXTICR2 &= (~(0xFF << (inputEvent % 4 * 8)));
        EXTI->EXTICR2 |= (gpioGroup << (inputEvent % 4 * 8));
        break;
    case 2:
        EXTI->EXTICR3 &= (~(0xFF << (inputEvent % 4 * 8)));
        EXTI->EXTICR3 |= (gpioGroup << (inputEvent % 4 * 8));
        break;
    case 3:
        EXTI->EXTICR4 &= (~(0xFF << (inputEvent % 4 * 8)));
        EXTI->EXTICR4 |= (gpioGroup << (inputEvent % 4 * 8));
        break;
    }


	// 2. 设置KEY1按键为下降沿检测          EXTI_FTSR1[9] = 0x1
    if (edge != RISING) {
        EXTI->FTSR1 |= (0x1 << inputEvent);
    } else {
        EXTI->RTSR1 |= (0x1 << inputEvent);
    }
	// 3. 使能EXTI9中断                    EXTI_C1IMR1[9] = 0x1
    EXTI->C1IMR1 |= (0x1 << inputEvent);
}

void hal_exti_IT_clear(input_event_t inputEvent, edge_trigger_select_t edge)
{
    if (edge != RISING) {
        EXTI->FPR1 |= (0x1 << inputEvent);
    } else {
        EXTI->RPR1 |= (0x1 << inputEvent);
    }
}

// KEY1->PF9->EXTI9-->中断号为99
void hal_gic_IT_init(unsigned int id, unsigned int pri)
{
	// 1. 设置GICD层的中断使能   GICD_ISENABLER3[3] = 0x1
    GICD->ISENABLER[id/32] |= (0x1 << (id%32));
	// 2. 设置GICD层的中断优先级   GICD_IPRIORITYR24[31:27] = 自己定义 范围0-31
    GICD->IPRIORITYR[id/4] &= ~(0x1F << (id%4*8+3));
    GICD->IPRIORITYR[id/4] |= (pri << (id%4*8+3));
	// 3. 设置GICD层中断目标分配   GICD_ITARGETSR24[25:24] = 0x1
    GICD->ITARGETSR[id/4] &= ~(0x3 << (id%4*8));
    GICD->ITARGETSR[id/4] |= (0x1 << (id%4*8));
	// 4. 设置GICD层全局中断使能   GICD_CTLR[0] = 0x1
    GICD->CTRL |= (0x1 << 0);
    
    // 5. 设置GICC层中断优先级屏蔽 GICC_PMR[7:3] = 0x1F  自己也可以给其他值
    GICC->PMR |= (0x1F << 3);
    // 6. 设置GICC层全局中断使能   GICC_CTLR[0] = 0x1
    GICC->CTRL |= (0x1 << 0);
}

void hal_gic_IT_clear(unsigned int id)
{
    GICD->ICPENDR[id/32] |= (0x1 << (id % 32));
}